package myicesscheduler.web;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class AdminMenuController extends SimpleFormController
{
   protected final Log logger = LogFactory.getLog( getClass() );
   private static final String URL = "adminMenu.spring";

   public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response )
         throws Exception
   {
      if( false == LoginController.isAdmin( request ) ) return LectureListController.redirect();

      final List< MyFileInfo > backupFiles = getBackupFilesInfo();

      final List< MyFileInfo > hackUploadList = new LinkedList< MyFileInfo >();
      final List< MyFileInfo > hackDbList = new LinkedList< MyFileInfo >();
      final MyFileInfo hackFileInfo = new MyFileInfo();
      hackFileInfo.setFilename( "fakeFilename" );
      hackFileInfo.setDir( "fakeDir" );
      hackFileInfo.setFileSizeInByte( 10000 );
      hackUploadList.add( hackFileInfo );
      hackDbList.add( hackFileInfo );

      final ModelAndView mv = new ModelAndView( "adminMenu" );
      mv.addObject( "backupFiles", backupFiles );
      mv.addObject( "restoreUploadBackupFiles", hackUploadList );
      mv.addObject( "restoreDatabaseBackupFiles", hackDbList );
      return mv;
   }

   public static List< MyFileInfo > getBackupFilesInfo()
   {
      final List< MyFileInfo > rst = new LinkedList< MyFileInfo >();

      final String[] filenames = AdminBackupCompressController.getZipBackupFilenames();
      for( final String filename : filenames )
      {
         final String fullFilename = MyFolderUtil.backupFolder.getAbsolutePathOfFile( filename );
         final File fh = new File( fullFilename );
         if( false == fh.exists() ) continue;

         final MyFileInfo fileInfo = new MyFileInfo();
         fileInfo.setFilename( filename );
         fileInfo.setDir( "backup" );
         fileInfo.setFileSizeInByte( fh.length() );
         rst.add( fileInfo );
      }

      return rst;
   }

   @Override
   protected Object formBackingObject( HttpServletRequest request ) throws Exception
   {
      return new AdminMenuCommand();
   }

   @Override
   protected ModelAndView onSubmit( Object command ) throws Exception
   {
      return super.onSubmit( command );
   }

   public static ModelAndView redirect()
   {
      return new ModelAndView( new RedirectView( URL ) );
   }

   public static ModelAndView redirect_toAnchor( String anchorName )
   {
      return new ModelAndView( new RedirectView( URL + "#" + anchorName ) );
   }

}
